//
//  HKBaseWebViewController.m
//  HKUtilities
//
//  Created by 胡锦涛 on 2018/11/14.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

#import "HKBaseWebViewController.h"
#import "HKPrefixHeader.h"
#import "MJRefresh.h"
@interface HKBaseWebViewController ()
@end

@implementation HKBaseWebViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.showShare = YES;
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.webView) {
        [self.webView evaluateJavaScript:@"HKWebListener('viewAppear')" completionHandler:nil];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.webView) {
        [self.webView evaluateJavaScript:@"HKWebListener('viewDisappear')" completionHandler:nil];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.backItem;
    [self setNavBarBgColor:HKHexColor(0xFF55C9C4)];
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, self.navigationController.navigationBar.height-2, SCREEN_WIDTH, 2)];
    self.progressView.progressTintColor = [UIColor whiteColor];
    self.progressView.trackTintColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor clearColor];
    //self.webView.scrollView.backgroundColor = [UIColor redColor];
    [self.navigationController.navigationBar addSubview:self.progressView];
}
-(void)refreshWithUrl:(NSString*)url {
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    if(APPCookie){
        [requset addValue:APPCookie forHTTPHeaderField:@"Cookie"];
    }
    [self.webView loadRequest:requset];
}
-(void)loadWithUrl:(NSString *)url{
    self.urlString = url;
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    if(APPCookie){
        [requset addValue:APPCookie forHTTPHeaderField:@"Cookie"];
    }
    [self.webView loadRequest:requset];
}

-(void)reload{
    
    if (self.urlString) {
        [self loadWithUrl:self.urlString];
    }else{
        [self.webView reload];
    }
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{
    if (object == self.webView) {
        if ([keyPath isEqualToString:@"title"]) {
            self.navigationItem.title = change[@"new"];
        }
        else if ([keyPath isEqualToString:@"estimatedProgress"]) {
            [self.progressView setProgress:[change[@"new"] floatValue] animated:YES];
        }
        if (!self.webView.isLoading) {
            [UIView animateWithDuration:0.5f animations:^{
                self.progressView.alpha = 0;
                [self.progressView setProgress:0 animated:NO];
            }];
        }else{
            self.progressView.alpha = 1.0;
        }
    }
}

#pragma mark --- WKNavigationDelegate----
//开始请求
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    self.progressView.alpha = 1.0;
    [self.loadingView addTo:_webView];
}

//开始返回内容
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    [self.webView.scrollView.mj_header endRefreshing];
}

//结束请求
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self.webView.scrollView.mj_header endRefreshing];
    [self.loadingView dismiss];
    
//    [self.webView evaluateJavaScript:@"document.body.offsetHeight"completionHandler:^( id _Nullable result,NSError * _Nullable error) {
//        //获取页面高度，并重置webview的frame
//        double webViewHeight = [result doubleValue];
//        CGRect frame =webView.frame;
//        frame.size.height =webViewHeight;
//        webView.frame = frame;
//    }];
}

-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSString *errorMessage =@"网络请求异常，\n点击重试";
    HKWeakSelf
    [self.loadingView showErrorMessage:errorMessage WithRetry:^{
        HKStrongSelf
        [self reload];
    }];
}

// 决定导航的动作，通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制，不允许跨域，因此我们要对不能跨域的链接
// 单独处理。但是，对于Safari是允许跨域的，不用这么处理。
//请求前
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    self.progressView.alpha = 1.0;
    // NOTE: ------  对alipays:相关的scheme处理 -------
    // NOTE: 若遇到支付宝相关scheme，则跳转到本地支付宝App
    NSString* reqUrl = navigationAction.request.URL.absoluteString;
    if ([reqUrl hasPrefix:@"alipays://"] || [reqUrl hasPrefix:@"alipay://"]) {

        if (![[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"alipay:"]]) {
            //未安装支付宝客户端
            [self showAlertWithTitle:@"提示" message:@"未检测到支付宝客户端，请安装后重试。" cancelTitle:@"立即安装" defaultTitle:nil distinct:nil cancel:^{
                //FIXME:跳转itune下载支付宝App
                NSString* urlStr = @"https://itunes.apple.com/cn/app/zhi-fu-bao-qian-bao-yu-e-bao/id333206289?mt=8";
                NSURL *downloadUrl = [NSURL URLWithString:urlStr];
                [[UIApplication sharedApplication]openURL:downloadUrl];
            } confirm:nil];
        }else {
            [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
            [self.view removeAllSubviews];
        }
    }
    //处理 Url
    if ([navigationAction.request.URL.scheme isEqualToString:HK_APP_SCHEME]) {
        //NSString *url = navigationAction.request.URL.absoluteString;
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    if(!([navigationAction.request.URL.scheme isEqualToString:@"http"] || [navigationAction.request.URL.scheme isEqualToString:@"https"])){
        if([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            });
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    self.urlString = navigationAction.request.URL.absoluteString;
    decisionHandler(WKNavigationActionPolicyAllow);
}

//请求回来的数据
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    /**
     *WKNavigationResponsePolicyCancel,
     WKNavigationResponsePolicyAllow,
     */
    decisionHandler(WKNavigationResponsePolicyAllow);
}

//接收到服务器跳转请求之后调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

//网页中有target="_blank" 在新窗口打开链接 需要实现此方法
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (navigationAction.targetFrame.isMainFrame == NO){
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
#pragma mark---------WKUIDelegate 弹框相关------
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([alert.textFields firstObject].text);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

// - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    if ([message.name isEqualToString:JSObjectName]) {
        if ([message.body length]) {
            NSDictionary *dict = [message.body HK_jsonDictionary];
            if (dict[@"method"]) {
                SEL selector;
                id params = dict[@"params"];
                selector = NSSelectorFromString(dict[@"method"]);
                if (params && [params isKindOfClass:[NSString class]] ) {
                    if ([params length]) {
                        selector = NSSelectorFromString([NSString stringWithFormat:@"%@:", dict[@"method"]]);
                    }
                }
                // 调用方法
                if ([self respondsToSelector:selector]) {
                    if ([dict[@"callback"] length]) {
                        self.callbackName = dict[@"callback"];
                    }
                    [self performSelectorOnMainThread:selector withObject:[dict[@"params"] length]?dict[@"params"]:nil waitUntilDone:YES];
                } else {
                    NSLog(@"未找到方法：%@", dict[@"method"]);
                }
            }
        }
    }
}

#pragma mark - init

- (UIBarButtonItem *)backItem {
    if (!_backItem) {
        _backItem = [UIBarButtonItem getItemWithImageName:@"HK_GroupBack" withTarget:self action:@selector(backNative)];
    }
    return _backItem;
}
- (UIBarButtonItem *)closeItem {
    if (!_closeItem) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"关闭" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(closeNative) forControlEvents:UIControlEventTouchUpInside];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        [btn sizeToFit];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, -36, 0, 0);
        btn.frame = CGRectMake(0, 0, 40, 40);
        _closeItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        
    }
    return _closeItem;
}
- (void)backNative {
    if ([self.webView canGoBack]) {
        self.urlString = @"";
        [self.webView goBack];
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    } else {
        [self closeNative];
    }
}

- (void)closeNative {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didTitleBarOptionSelected:(NSNumber *)index
{
    [self.webView evaluateJavaScript:@"getShareLink();" completionHandler:^(id _Nullable jsShareUrl, NSError * _Nullable error) {
        NSLog(@"分享链接%@",jsShareUrl);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"WebView内存泄漏%@",self.class);
}

-(HKProgressView *)loadingView{
    if (!_loadingView) {
        _loadingView = [[HKProgressView alloc]init];
    }
    return _loadingView;
}

-(void)dealloc{
    if (self.webView) {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
        [self.webView removeObserver:self forKeyPath:@"title" context:nil];
        [self.webView removeObserver:self forKeyPath:@"loading" context:nil];
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JSObjectName];
        self.webView.UIDelegate = nil;
        self.webView.navigationDelegate = nil;
        [self.webView removeAllSubviews] ;
        if (self.progressView) {
            [self.progressView removeFromSuperview];
        }
    }
}
@end
